package com.op.teachingliteapp.fragment;

import android.graphics.Bitmap;
import android.graphics.RectF;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import com.op.teachingliteapp.R;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.op.teachingliteapp.sender.*;
import com.op.teachingliteapp.sender.Runtime;
import com.op.teachingliteapp.sender.runnable.SenderRunnable;
import org.vudroid.core.codec.CodecContext;
import org.vudroid.core.codec.CodecDocument;
import org.vudroid.core.codec.CodecPage;
import org.vudroid.pdfdroid.codec.PdfContext;

public class PPTShowFragment extends Fragment {
    private int pageCount;
    private CodecContext pdf_conext;
    private ImageView pptView;
    private CodecDocument pdf_documen;
    private int index;
    private SeekBar pptSeekbar;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_ppt_show, container, false);


        pptView = (ImageView) root.findViewById(R.id.pptView);

        pdf_conext = new PdfContext();
        String url = getArguments().getString("url");
        Log.i("PPTShowFragment", "--------" + url + "----------");
        pdf_documen = pdf_conext.openDocument(url);
        pageCount = pdf_documen.getPageCount();
        index = 0;
        pptSeekbar = (SeekBar) root.findViewById(R.id.seekBar);
        pptSeekbar.setMax(pageCount - 1);
        pptSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {



            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int pageIndex = seekBar.getProgress();
                Log.i("PPTShowFragment", "------------" + pageIndex+1 + "-------------");
                changePage(pageIndex);

            }
        });

        changePage(index);


        return root;
    }



    @Override
    public void onDestroyView() {
        new Thread(new SenderRunnable(Runtime.ip, Constants.teacherPort, null)).start();
        super.onDestroyView();
    }

    private void changePage(int i) {


        CodecPage pdf_page = pdf_documen.getPage(i);
        RectF rf = new RectF();
        rf.bottom = rf.right = (float) 1.0;
        int w = pdf_page.getWidth();
        int h = pdf_page.getHeight();
        Bitmap bitmap = pdf_page.renderBitmap(w, h, rf);
        pptView.setImageBitmap(bitmap);

        new Thread(new SenderRunnable(Runtime.ip, Constants.teacherPort, pptView)).start();


    }


}
